package root.electronclass.electronclass.personal.activity

import android.Manifest
import android.app.Activity.RESULT_OK
import android.app.DatePickerDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.view.View
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import retrofit2.Call
import root.electronclass.electronclass.R
import root.electronclass.electronclass.common.base.ViewBindingFragment
import root.electronclass.electronclass.common.util.HeadUtil
import root.electronclass.electronclass.databinding.ActivityPersonalInfoBinding
import root.electronclass.electronclass.mvp.GlobalParameter
import root.electronclass.electronclass.mvp.base.BaseResponse
import root.electronclass.electronclass.mvp.base.CallbackNext
import root.electronclass.electronclass.mvp.entity.UserInfoStudent
import root.electronclass.electronclass.mvp.rest.RestManager
import java.io.File

class PersonalInfoFragment : ViewBindingFragment<ActivityPersonalInfoBinding>() {
    lateinit var data: UserInfoStudent
    private var dataTime: DatePickerDialog? = null
    private var file: File? = null
    private val CAMERA_PERMISSION_CODE = 100
    private val STORAGE_PERMISSION_CODE = 101
    private val REQUEST_IMAGE_CAPTURE = 2000

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        data = arguments?.getSerializable("data") as UserInfoStudent
        binding.name.text = data.name.orEmpty()
        binding.time.text = data.joinDate
        binding.gender.text = data.gender
        binding.certificateNo.text = data.zkzh.orEmpty()
        height = if (data.userInfoVo.sg == null) 0 else data.userInfoVo.sg
        weight = if (data.userInfoVo.tz == null) 0 else data.userInfoVo.tz
        binding.heightTv.text = height.toString()
        binding.weight.text = weight.toString()
        binding.studentType.text = data.studentType
        binding.idNumber.text = data.cardId.orEmpty()
        binding.nomenclature.text = data.userInfoVo.nation
        binding.nativePlace.text = data.userInfoVo.nativePlace
        binding.node.text = data.userInfoVo.joinYear
        binding.studyNum.text = data.userNo
        file = File(
            view.context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS),
            "picture" + System.currentTimeMillis() / 1000 + ".jpg"
        )

        val zzmm = resources.getStringArray(R.array.zzmm)
        for (i in zzmm.indices) {
            if (zzmm[i] == data.userInfoVo.zzmm.toString()) {
                binding.politics.setSelection(i)
            }
        }

        if (data.userInfoVo.facePhotoFormat == null || data.userInfoVo.facePhotoFormat.size == 0) {
            val pic = HeadUtil.getHeadPic(if (data.gender == "女") 2 else 3)
            binding.ivHead.setActualImageResource(pic)
        } else {
            binding.ivHead.setImageURI(data.userInfoVo.facePhotoFormat[0].url)
        }

        onClick()
    }

    private var height = 0
    private var weight = 0

    private fun onClick() {
        binding.ivHeightJian.setOnClickListener {
            if (height == 0) {
                return@setOnClickListener
            }
            height--
            binding.heightTv.text = height.toString()
        }

        binding.ivHeigthJia.setOnClickListener {
            height++
            binding.heightTv.text = height.toString()
        }

        binding.ivWeightJian.setOnClickListener {
            if (weight == 0) {
                return@setOnClickListener
            }
            weight--
            binding.weight.text = weight.toString()
        }

        binding.ivWeightJia.setOnClickListener {
            weight++
            binding.weight.text = weight.toString()
        }

        binding.upgrade.setOnClickListener {
            edit()
        }


        binding.updateHead.setOnClickListener {
//            // 检查相机权限
            val activity = activity ?: return@setOnClickListener
            if (ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(
                    activity,
                    arrayOf(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE),
                    CAMERA_PERMISSION_CODE
                )
            } else {
                openCamera()
            }
        }
    }


    private fun edit() {
        data.userInfoVo.sg = height
        data.userInfoVo.tz = weight
        RestManager.getInstance().initRest().editStudent(data)
            .enqueue(object : CallbackNext<BaseResponse<UserInfoStudent>>(mDialogViewModel) {
                override fun onSuccessful(
                    call: Call<BaseResponse<UserInfoStudent>>?,
                    response: BaseResponse<UserInfoStudent>
                ) {
                    if (response.isSuccess) {
                        GlobalParameter.setSTUDENT(response.rows)
                        toast("修改成功")
                    }

                }

                override fun onError(
                    call: Call<BaseResponse<UserInfoStudent>>?,
                    response: BaseResponse<UserInfoStudent>?
                ) {
                    toast(response?.msg)

                }

            })
    }


    /**
     * 修改头像
     */
    private fun editFace(path: String) {
        val file = File(path)
        val requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file)
        val body = MultipartBody.Part.createFormData("file", file.name, requestBody)

        RestManager.getInstance().initRest().editFace(body, GlobalParameter.getSTUDENT().id)
            .enqueue(object : CallbackNext<BaseResponse<UserInfoStudent>>(mDialogViewModel) {
                override fun onSuccessful(
                    call: Call<BaseResponse<UserInfoStudent>>?,
                    response: BaseResponse<UserInfoStudent>
                ) {
                    if (response.isSuccess) {
                        getData()
                        toast("修改成功")
                    }

                }

                override fun onError(
                    call: Call<BaseResponse<UserInfoStudent>>?,
                    response: BaseResponse<UserInfoStudent>?
                ) {
                    toast(response?.msg)

                }

            })
    }

    private fun getData() {
        RestManager.getInstance().initRest().student().enqueue(object : CallbackNext<BaseResponse<UserInfoStudent>>(mDialogViewModel) {
            override fun onSuccessful(
                call: Call<BaseResponse<UserInfoStudent>>?, response: BaseResponse<UserInfoStudent>
            ) {
                if (response.isSuccess) {
                    data = response.rows as UserInfoStudent
                    GlobalParameter.setSTUDENT(data)
                    if (data.userInfoVo.facePhotoFormat == null || data.userInfoVo.facePhotoFormat.size == 0) {
                        val pic = HeadUtil.getHeadPic(if (data.gender == "女") 2 else 3)
                        binding.ivHead.setActualImageResource(pic)
                    } else {
                        binding.ivHead.setImageURI(GlobalParameter.getSTUDENT().userInfoVo.facePhotoFormat[0].url)
                    }
                }
            }

            override fun onError(
                call: Call<BaseResponse<UserInfoStudent>>?, response: BaseResponse<UserInfoStudent>?
            ) {
                dismissProgress()
            }

        })
    }

    private fun openCamera() {
        val activity = activity ?: return
        val pictureFile =
            FileProvider.getUriForFile(activity, "root.electronclass.electronclass.provider", file!!)
        val mIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        mIntent.putExtra(MediaStore.EXTRA_OUTPUT, pictureFile)
        mIntent.putExtra(MediaStore.Images.Media.ORIENTATION, 0)
        startActivityForResult(mIntent, REQUEST_IMAGE_CAPTURE)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == CAMERA_PERMISSION_CODE) {
            if (grantResults.isNotEmpty() && grantResults.all { it == PackageManager.PERMISSION_GRANTED }) {
                // 权限被授予，执行相机操作
                openCamera()
            } else {
                // 权限被拒绝，处理权限被拒绝的情况
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            editFace(file!!.absolutePath)
        }
    }


}